"""应用程序配置管理。

本模块处理环境特定的配置加载、解析和管理
用于应用程序。它包括环境检测、.env 文件加载和
配置值解析。
"""

import json
import os
from enum import Enum
from pathlib import Path
from typing import (
    Any,
    Dict,
    List,
    Optional,
    Union,
)

from dotenv import load_dotenv


# Define environment types
class Environment(str, Enum):
    """应用程序环境类型。

    定义应用程序可以运行的可能环境：
    development, staging, production, 和 test。
    """

    DEVELOPMENT = "development"
    STAGING = "staging"
    PRODUCTION = "production"
    TEST = "test"


# Determine environment
def get_environment() -> Environment:
    """Get the current environment.

    Returns:
        Environment: The current environment (development, staging, production, or test)
    """
    env = os.getenv("ENVIRONMENT", Environment.DEVELOPMENT.value).lower()
    try:
        return Environment(env)
    except ValueError:
        return Environment.DEVELOPMENT


# Load environment variables from .env file
# Use different .env files for different environments
env_file = Path(f".env.{get_environment().value}")
print(env_file)
if env_file.exists():

    print("env_file存在")
    load_dotenv(env_file)
else:
    print("env_file不存在")
    load_dotenv()  # Load default .env file if environment-specific file doesn't exist

# Application settings
class Settings:
    """应用程序配置设置。

    该类管理应用程序的所有配置设置，包括：
    - 环境配置
    - 安全设置
    - 数据库配置
    - LLM配置
    - 外部认证配置
    """
    
    # 环境配置
    ENVIRONMENT: Environment = get_environment()
    DEBUG: bool = os.getenv("DEBUG", "False").lower() == "true"
    
    # 应用程序基本信息
    PROJECT_NAME: str = os.getenv("PROJECT_NAME", "Web Assistant")
    VERSION: str = os.getenv("VERSION", "1.0.0")
    DESCRIPTION: str = os.getenv("DESCRIPTION", "A FastAPI application with LangGraph integration")
    API_V1_STR: str = os.getenv("API_V1_STR", "/api/v1")
    
    # 安全设置
    SECRET_KEY: str = os.getenv("SECRET_KEY", "JWTTEST")
    JWT_SECRET_KEY: str = os.getenv("JWT_SECRET_KEY", SECRET_KEY)
    JWT_ALGORITHM: str = os.getenv("JWT_ALGORITHM", "HS256")
    JWT_ACCESS_TOKEN_EXPIRE_DAYS: int = int(os.getenv("JWT_ACCESS_TOKEN_EXPIRE_DAYS", "30"))
    
    # 外部认证设置
    EXTERNAL_AUTH_ENABLED: bool = os.getenv("EXTERNAL_AUTH_ENABLED", "False").lower() == "true"
    EXTERNAL_AUTH_ISSUER: str = os.getenv("EXTERNAL_AUTH_ISSUER", "")
    EXTERNAL_AUTH_AUDIENCE: str = os.getenv("EXTERNAL_AUTH_AUDIENCE", "")
    EXTERNAL_AUTH_JWKS_URI: str = os.getenv("EXTERNAL_AUTH_JWKS_URI", "")
    
    # 数据库配置
    DATABASE_URL: str = os.getenv("DATABASE_URL", "sqlite+aiosqlite:///./test.db")
    DATABASE_POOL_SIZE: int = int(os.getenv("DATABASE_POOL_SIZE", "10"))
    DATABASE_MAX_OVERFLOW: int = int(os.getenv("DATABASE_MAX_OVERFLOW", "20"))
    POSTGRES_URL: str = os.getenv("POSTGRES_URL", "postgresql://postgres:123456@127.0.0.1:5432/ti-smart")
    POSTGRES_POOL_SIZE: int = int(os.getenv("POSTGRES_POOL_SIZE", "10"))
    POSTGRES_MAX_OVERFLOW: int = int(os.getenv("POSTGRES_MAX_OVERFLOW", "20"))

    # redis 与 embedding配置
    REDIS_URL: str = os.getenv("REDIS_URL", "redis://192.168.51.130:6380")
    DASHSCOPE_API_KEY: str = os.getenv("DASHSCOPE_API_KEY", "sk-3815bc7f8901434e97ed70757d61e957")
    EMBEDDING_MODEL=os.getenv("EMBEDDING_MODEL", "text-embedding-v1")
    # LLM配置
    LLM_BASE_URL: str = os.getenv("LLM_BASE_URL", "https://api.deepseek.com/v1")
    LLM_API_KEY: str = os.getenv("LLM_API_KEY", "sk-cb3aacb93d554d53a0890c5b00d6faa9")
    LLM_MODEL: str = os.getenv("LLM_MODEL", "deepseek-chat")
    LLM_TEMPERATURE: float = float(os.getenv("LLM_TEMPERATURE", "0.7"))
    DEFAULT_LLM_TEMPERATURE: float = float(os.getenv("DEFAULT_LLM_TEMPERATURE", "0.7"))
    LLM_MAX_TOKENS: int = int(os.getenv("LLM_MAX_TOKENS", "2048"))
    MAX_TOKENS: int = int(os.getenv("MAX_TOKENS", "2048"))
    MAX_LLM_CALL_RETRIES: int = int(os.getenv("MAX_LLM_CALL_RETRIES", "5"))
    
    # Rate limiting
    RATE_LIMIT: str = os.getenv("RATE_LIMIT", "100/minute")
    RATE_LIMIT_ENABLED: bool = os.getenv("RATE_LIMIT_ENABLED", "True").lower() == "true"
    RATE_LIMIT_DEFAULT: str = os.getenv("RATE_LIMIT_DEFAULT", "100/minute")
    RATE_LIMIT_ENDPOINTS: Dict[str, List[str]] = {
        "root": [os.getenv("RATE_LIMIT_ROOT", "100/minute")],
        "health": [os.getenv("RATE_LIMIT_HEALTH", "100/minute")],
        "chat": [os.getenv("RATE_LIMIT_CHAT", "100/minute")],
        "chat_stream": [os.getenv("RATE_LIMIT_CHAT_STREAM", "100/minute")],
        "messages": [os.getenv("RATE_LIMIT_MESSAGES", "200/minute")],
    }
    
    # CORS 配置
    CORS_ORIGINS: List[str] = json.loads(os.getenv("CORS_ORIGINS", '["*"]'))
    ALLOWED_ORIGINS: List[str] = json.loads(os.getenv("ALLOWED_ORIGINS", '["*"]'))
    CORS_CREDENTIALS: bool = os.getenv("CORS_CREDENTIALS", "True").lower() == "true"
    CORS_METHODS: List[str] = json.loads(os.getenv("CORS_METHODS", '["*"]'))
    CORS_HEADERS: List[str] = json.loads(os.getenv("CORS_HEADERS", '["*"]'))
    
    # 日志配置
    LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO").upper()
    LOG_FORMAT: str = os.getenv("LOG_FORMAT", "json")
    LOG_DIR: Path = Path(os.getenv("LOG_DIR", "./logs"))
    
    # Langfuse 配置
    LANGFUSE_ENABLED: bool = os.getenv("LANGFUSE_ENABLED", "False").lower() == "true"
    LANGFUSE_SECRET_KEY: str = os.getenv("LANGFUSE_SECRET_KEY", "")
    LANGFUSE_PUBLIC_KEY: str = os.getenv("LANGFUSE_PUBLIC_KEY", "")
    LANGFUSE_HOST: str = os.getenv("LANGFUSE_HOST", "https://cloud.langfuse.com")
    
    # Prometheus 配置
    PROMETHEUS_ENABLED: bool = os.getenv("PROMETHEUS_ENABLED", "True").lower() == "true"
    
    # 评估配置
    EVALUATION_LLM: str = os.getenv("EVALUATION_LLM", "gpt-4o-mini")
    EVALUATION_API_KEY: str = os.getenv("EVALUATION_API_KEY", "")
    EVALUATION_BASE_URL: str = os.getenv("EVALUATION_BASE_URL", "https://api.openai.com/v1")
    EVALUATION_SLEEP_TIME: float = float(os.getenv("EVALUATION_SLEEP_TIME", "0.1"))

    # 沙箱配置
    SANDBOX_FUSION_ENDPOINT: str = os.getenv("SANDBOX_FUSION_ENDPOINT", "")
# 创建设置实例
settings = Settings()